from settings import URL_ROOT

from django.http import HttpResponse
from django.shortcuts import render_to_response,redirect

from myuser.models import MyUser
from doubancon.models import Douban_Access_Token
from weibo.models import Sina_Access_Token
from myuser.usercheck import getUser

from myuser.usercheck import checkSinaAccessToken,checkDoubanAccessToken
from myuser.usercheck import checkUserNameValid,checkEmailValid
from myuser.usercheck import getSiteUser
from myuser.usercheck import isSinaConnect,isDoubanConnect

from weibo.weibofunc import getWeiboInfoById
from doubancon.doubanfunc import getDoubanInfoById

from settings import LONGCOOKIETIME,SHORTCOOKIETIME

import logging
import simplejson

loginurl = URL_ROOT+"/basicuser/login"

def login(request):
    """
    myuser manager
    get : show the login 
    post : check the login info, insert the cookie, redicrect to the call back usl
    """
    #return HttpResponse("login")
    if request.method == 'POST':
        # check user
        #print 2
        name = request.POST['username']
        pwd = request.POST['password']

        #set cookie
        if MyUser.all().filter("nickname = ",name).filter("pwd = ",pwd).count() == 1:
            #login success
            #return HttpResponse("ok")
            #res = redirect(URL_ROOT)
            dic = {}
            dic['theurl'] = URL_ROOT
            dic['thedesp'] = "login ok"
            res = render_to_response("tools/redirect.html",dic)
            curuser =  MyUser.all().filter("nickname = ",name).filter("pwd = ",pwd)[0]
            res.set_cookie("key",curuser.key(),LONGCOOKIETIME)
            res.set_cookie("pwd",pwd,LONGCOOKIETIME)
            return res

        else:
            dic = {}
            dic['theurl'] = URL_ROOT+"/basicuser/login"
            dic['thedesp'] = "name or password wrong"
            return render_to_response("tools/redirect.html",dic)


    elif request.method == 'GET':
        #print 1
        dic = {}
        return render_to_response("myuser/login.html",dic)
    else:
        logging.debug("unknow method")

URL_REG = URL_ROOT+"/basicuser/reg"
def reg(request):
    """
    check get or post
    the email info and the password info
    """
    if request.method == 'POST':
        # check user
        name = request.POST['username']
        email = request.POST['email']
        pwd = request.POST['password']

        dic = {}
        dic['theurl'] = URL_REG
        if checkUserNameValid(name) == False:
            dic['thedesp'] = "username error"
            return render_to_response("tools/redirect.html",dic)
        if checkEmailValid(email) == False:
            dic['thedesp'] = "email error"
            return render_to_response("tools/redirect.html",dic)

        newuser = MyUser()
        newuser.nickname = name
        newuser.email = email
        newuser.pwd = pwd
        newuser.put()

        #dic = {}
        dic['theurl'] = URL_ROOT
        dic['thedesp'] = "reg ok"
        res = render_to_response("tools/redirect.html",dic)
        res.set_cookie("key",newuser.key(),LONGCOOKIETIME)
        res.set_cookie("pwd",pwd,LONGCOOKIETIME)
        return res
    elif request.method == 'GET':
        dic = {}
        return render_to_response("myuser/reg.html",dic)
    else:
        logging.debug("unknow method")

    return HttpResponse("reg")

def logout(request):
    """
    clear all the cookie of this user
    redirect to the main page
    """
    dic = {}
    dic['theurl'] = URL_ROOT
    dic['thedesp'] = "logout success"
    hr = render_to_response("tools/redirect.html",dic)
    for k in request.COOKIES.keys():
        hr.delete_cookie(k)
    return hr

def connectstatus(request):
    """
    show the connection status of this user
    douban status
    sina status
    """
    dic = {}
    user = getUser(request)
    if not user == None:
        dic['user'] = user
    if isSinaConnect(user.key()):
        dic['sinacon'] = '1'
    if isDoubanConnect(user.key()):
        dic['doubancon'] = '1'
    return render_to_response("myuser/connectstatus.html",dic)
    #return HttpResponse("connect status")

def conNewUser(request):

    """
    should get the info the connect
    GET: return the page for new_user_connection
    POST:create a new user if success,redirect to connection page
    """
    #dinfo = checkDoubanAccessToken(request)
    #sinfo = checkSinaAccessToken(request)
    #here how to not get by the cookie?directly directe by the save oauth

    dic = {}
    dic['debuginfo'] = simplejson.dumps(request.COOKIES)

    #rediret to here from the connect exist user
    if request.method == 'GET':
        dic['username'] = request.GET['username']
        if request.GET.has_key("doubanid"):
            dic['doubanid'] = request.GET['doubanid']
        else:
            dic['doubanid'] = ""
        if request.GET.has_key("sinaid"):
            dic['sinaid'] = request.GET['sinaid']
        else:
            dic['sinaid'] = ""

        return render_to_response("myuser/conNewUser.html",dic)
        #return HttpResponse("no get access")
    elif request.method == "POST":
        #check the username,email,pwd,cpwd
        name = request.POST['username']
        email = request.POST['email']
        pwd = request.POST['pwd']

        sinfo = None
        dinfo = None

        #if request.POST.has_key("doubanid") and request.POST['doubanid'] != "":
        if request.POST.has_key("doubanid"):
            dinfo = getDoubanInfoById(request.POST['doubanid'])
            if dinfo.userref != None:
                #login this user
                raise Excetion("post user has already connect a site user, need handler here")
        
        if request.POST.has_key("sinaid"):
            sinfo = getWeiboInfoById(request.POST['sinaid'])

        
        dic['theurl']= URL_ROOT
        if checkUserNameValid(name) == False:
            dic['thedesp'] = "username has been occupied"
            return render_to_response("tools/redirect.html",dic)
        if checkEmailValid(email) == False:
            dic['thedesp'] = "email has been used"
            return render_to_response("tools/redirect.html",dic)

        curuser = MyUser()
        curuser.nickname = name
        curuser.email = email
        curuser.pwd = pwd
        curuser.put()

        if sinfo != None:
            sinfo.userref = curuser.key()#?
            sinfo.put()

        if dinfo != None:
            dinfo.userref = curuser.key()
            dinfo.put()
        
        #here need to login the user
        dic['theurl'] = URL_ROOT
        dic['thedesp'] = "link success"
        hr = render_to_response("tools/redirect.html",dic)
        #hr.set_cookie("id",curuser.id,LONGCOOKIETIME)
        #return HttpResponse(curuser.key())
        hr.set_cookie("key",curuser.key(),LONGCOOKIETIME)
        hr.set_cookie("pwd",pwd,LONGCOOKIETIME)

        return hr
            
def conExistUser(request):
    """
    should get the info of the connection
    if the exist user has already been connected,
    then login in the exist user and redirect to the connectstatus page

    GET: return the page
    POST:check the exist user,create the link

    """
    #dinfo = checkDoubanAccessToken(request)
    #sinfo = checkSinaAccessToken(request)

    if request.method == "GET":
        raise Exception("get is not permitted")
        if (dinfo == None and sinfo == None) or (dinfo != None and sinfo !=None):
            dic = {}
            dic['theurl'] = URL_ROOT
            dic['thedesp'] = "connection info error"
            hr =  render_to_response("tools/redirect.html",dic)
            return hr
    
        dic = {}
        if dinfo != None:
            dic['username'] = dinfo.doubanid
        elif sinfo != None:
            dic['username'] = sinfo.sinaid
            return render_to_response("myuser/conExistUser.html",dic)
    elif request.method == "POST":

        #check the sina con or doubancon
        #raise Exception("need change here")
        #here need to check the user connection info
        name = request.POST['username']
        pwd = request.POST['pwd']

        sinfo = None
        dinfo = None
        if request.POST.has_key("doubanid"):
            dinfo = getDoubanInfoById(request.POST['doubanid'])
            if dinfo.userref != None:
                #login this user
                raise Excetion("post user has already connect a site user, need handler here")
        elif request.POST.has_key("sinaid"):
            sinfo = getWeiboInfoById(request.POST['sinaid'])
        else:
            raise Exception("no connection info")


        #check site user valid
        user = getSiteUser(name,pwd)
        if user == None:
            dic = {}
            dic['theurl'] = URL_ROOT+"/basicuser/login"
            dic['thedesp'] = "name and pwd does not match"
            hr = render_to_response("tools/redirect.html",dic)
            for k in request.COOKIES.keys():
                hr.delete_cookie(k)
            return hr

        #check connection status of this user
        if dinfo != None:
            if isDoubanConnect(user.key()):#check douban connection
                dic = {}
                dic['theurl'] = URL_ROOT+'/basicuser/connectstatus'
                dic['thedesp'] = "your site account has connect a douban account"
                hr = render_to_response("tools/redirect.html",dic)
                for k in request.COOKIES.keys():
                    hr.delete_cookie(k)
                hr.set_cookie("key",user.key(),LONGCOOKIETIME)
                hr.set_cookie("pwd",user.pwd,LONGCOOKIETIME)
                return hr

        if sinfo != None:
             if isDoubanConnect(user.key()):#check sina connection
                dic = {}
                dic['theurl'] = URL_ROOT+'/basicuser/connectstatus'
                dic['thedesp'] = "your site account has connect a sina account"
                hr = render_to_response("tools/redirect.html",dic)
                for k in request.COOKIES.keys():
                    hr.delete_cookie(k)
                hr.set_cookie("key",user.key(),LONGCOOKIETIME)
                hr.set_cookie("pwd",user.pwd,LONGCOOKIETIME)
                return hr
        
        if dinfo != None:
            dinfo.userref = user.key()#?
            dinfo.put()
        if sinfo != None:
            sinfo.userref = user.key()
            sinfo.put()

        dic = {}
        dic['theurl'] = URL_ROOT
        dic['thedesp'] = "connection success"
        return render_to_response("tools/redirect.html",dic)

def checkUserName(request):
    """
    """
    thename = request.GET['name']
    dic ={}
    if checkUserNameValid(thename) == False:
        dic['status'] = "bad"
        return HttpResponse(simplejson.dumps(dic))
    else:
        dic['status'] = "good"
        return HttpResponse(simplejson.dumps(dic))




def checkEmail(request):
    """
    """
    dic = {}
    email = request.GET['email']
    if checkEmailValid(email) == False:
        dic['status'] = "bad"
        return HttpResponse(simplejson.dumps(dic))
    else:
        dic['status'] = "good"
        return HttpResponse(simplejson.dumps(dic))

def checkUsernamePwd(request):
    dic = {}
    if request.method == "GET":
        username = request.GET['username']
        pwd = request.GET['pwd']
        #check user exist
        #check user pwd match
        return HttpResponse("not implement")
    
def cancelDoubanCon(request):
    return HttpResponse("c d c not implement")

def cancelSinaCon(request):
    return HttpResponse("c s c not implement")
